import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exchange_records_logic.dart';
import '../../../gen/assets.gen.dart';

/// 兑换记录页面
class ExchangeRecordsView extends GetView<ExchangeRecordsLogic> {
  const ExchangeRecordsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 背景图
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Assets.points.detailBg.image(
              fit: BoxFit.cover,
              height: 300.h,
            ),
          ),
          Column(
            children: [
              // 固定头部区域
              _buildFixedHeader(),
              // 可滚动内容
              Expanded(
                child: _buildScrollableContent(),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 固定头部（包含标题和tab栏）
  Widget _buildFixedHeader() {
    return SafeArea(
      bottom: false,
      child: Column(
        children: [
          // 顶部导航栏
          _buildAppBar(),
          SizedBox(height: 30.h),
          // Tab栏
          _buildTabBar(),
        ],
      ),
    );
  }

  /// 顶部导航栏
  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
          Expanded(
            child: Text(
              '兑换记录',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ),
          SizedBox(width: 20.w), // 占位保持居中
        ],
      ),
    );
  }

  /// Tab栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10.w),
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: const Color(0xFF17181B),
        borderRadius: BorderRadius.circular(25.r),
      ),
      child: Obx(() => Row(
            children: [
              _buildTabItem('待付款', 0),
              _buildTabItem('待发货', 1),
              _buildTabItem('待收货', 2),
              _buildTabItem('已完成', 3),
            ],
          )),
    );
  }

  /// Tab项
  Widget _buildTabItem(String title, int index) {
    final isSelected = controller.state.selectedTabIndex.value == index;
    return Expanded(
      child: GestureDetector(
        onTap: () => controller.changeTab(index),
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFF282A2D) : Colors.transparent,
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Text(
            title,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }

  /// 可滚动内容
  Widget _buildScrollableContent() {
    return Container(
      margin: EdgeInsets.only(top: 14.h),
      child: Obx(() {
        final records = controller.filteredRecords;
        if (records.isEmpty) {
          return Center(
            child: Text(
              '暂无记录',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[500],
              ),
            ),
          );
        }
        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          itemCount: records.length,
          itemBuilder: (context, index) {
            return _buildRecordItem(records[index]);
          },
        );
      }),
    );
  }

  /// 记录项
  Widget _buildRecordItem(Map<String, dynamic> record) {
    final status = record['status'] as String;
    final statusText = controller.getStatusText(status);
    
    return GestureDetector(
      onTap: () => controller.viewOrderDetail(record['id']),
      child: Container(
        margin: EdgeInsets.only(bottom: 16.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: const Color(0xFF282725),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 时间和状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  record['time'],
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xffD9D9D9),
                  ),
                ),
                Text(
                  statusText,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFFF67F41),
                  ),
                ),
              ],
            ),
            SizedBox(height: 13.h),
            // 产品信息
            SizedBox(
              height: 80.w,
              child: Stack(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 产品图片
                      Container(
                        width: 80.w,
                        height: 80.w,
                        decoration: BoxDecoration(
                          color: Colors.grey[300],
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(16.r),
                          child: record['image'] != null
                              ? Image.network(
                                  record['image'],
                                  fit: BoxFit.cover,
                                  loadingBuilder: (context, child, loadingProgress) {
                                    if (loadingProgress == null) return child;
                                    return Center(
                                      child: CircularProgressIndicator(
                                        value: loadingProgress.expectedTotalBytes != null
                                            ? loadingProgress.cumulativeBytesLoaded /
                                                loadingProgress.expectedTotalBytes!
                                            : null,
                                        strokeWidth: 2,
                                      ),
                                    );
                                  },
                                  errorBuilder: (context, error, stackTrace) {
                                    return Center(
                                      child: Icon(
                                        Icons.broken_image,
                                        size: 30.sp,
                                        color: Colors.grey[500],
                                      ),
                                    );
                                  },
                                )
                              : Center(
                                  child: Icon(
                                    Icons.image,
                                    size: 30.sp,
                                    color: Colors.grey[500],
                                  ),
                                ),
                        ),
                      ),
                      SizedBox(width: 14.w),
                      // 产品名称和数量
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              record['productName'],
                              style: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w500,
                                color: Colors.white,
                              ),
                            ),
                            SizedBox(height: 4.h),
                            Text(
                              'X${record['quantity']}',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: const Color(0xFFF67F41),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 查看物流按钮（垂直居中）
                      if (status == 'pending_receipt' || status == 'completed')
                        Padding(
                          padding: EdgeInsets.only(top: 20.h),
                          child: GestureDetector(
                            onTap: () {
                              // 阻止事件冒泡到父级的 GestureDetector
                              controller.viewLogistics(record);
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.h),
                              decoration: BoxDecoration(
                                color: const Color(0xFFD9D9D9),
                                borderRadius: BorderRadius.circular(24.r),
                              ),
                              child: Text(
                                '查看物流',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                  // 实付积分（底部最右边）
                  Positioned(
                    bottom: 0,
                    right: 0,
                    child: Text(
                      '实付：${record['points']}积分',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
